package com.xnyzc.lhy.common.component.sms;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.xnyzc.lhy.common.entity.sms.AliCloudSMSTemplate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class AliCloudSMSUtils {

    private static String accessKeyId;

    private static String accessKeySecret;

    @Value("${global.ali.sms.accessKeyId}")
    public void setAccessKeyId(String keyId) {
        accessKeyId = keyId;
    }

    @Value("${global.ali.sms.accessKeySecret}")
    public void setAccessKeySecret(String keySecret) {
        accessKeySecret = keySecret;
    }

    /**
     * 单条短信发送
     * 使用QCloudSmsConstant获取短信模板，需要的参数按顺序放入msmData变量中
     *
     * @param phone      电话号码
     * @param template   短信模板
     * @param jsonObject 模板参数
     */
    public static void sendMessage(String phone, AliCloudSMSTemplate template, JSONObject jsonObject) {
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2017-05-25");
        request.setAction("SendSms");
        request.putQueryParameter("RegionId", "cn-hangzhou");
        request.putQueryParameter("PhoneNumbers", phone);
        request.putQueryParameter("SignName", template.getSignName());
        request.putQueryParameter("TemplateCode", template.getTemplateCode());
        if (jsonObject != null) {
            request.putQueryParameter("TemplateParam", jsonObject.toJSONString());
        }
        try {
            CommonResponse response = client.getCommonResponse(request);
            System.out.println(response.getData());
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }
    }
}
